import imp
from views.base import BaseHandler
import json,time
from util.myredis import r
from db.datab import db
from util.comm import md5
from util.myjwt import myjwt

#计算接口的执行时间
#写日志功能
#权限验证装饰器:两类接口共100个，50个读的，50个接口，读取的接口操作完跳转到a.html页面，写的接口跳转到b.html页面
# def pomition():
#     def is_login(func):
#         def wrapper(self,*args,**kargs):
#             #业务
#             #获取token
#             headers = self.request.headers
#             try:
#                 token = headers['token']
#                 flag = myjwt.jwt_check(token)
#                 if flag == True:
#                     #解析验证时间
#                     payload = myjwt.jwt_de(token)
#                     ptime = payload['data']['exp']
#                     now = time.time()
#                     if int(now)-int(ptime)>36:
#                          self.finish({"code":402})
#                     #  {"data": {"name": "zs", "userid": 1,'exp':}}
#                 else:
#                      self.finish({"code":403})
#             except:
#                  self.finish({"code":401})
#             #验证token
#             # headers['token']
#             #解析获取时间和当前时间对比
#             func(self,*args,**kargs)
#         return wrapper
#     return is_login

#计算接口的执行时间
#写日志功能
#权限验证装饰器:两类接口共100个，50个读的，50个接口，读取的接口操作完跳转到http://www.baidu.com页面，写的接口跳转到http://www.jd.com页面
# import time
# def getinterfacetime(type):
#     def interfacetime(func):
#         def wrapper(self):
#             func(self)
#             if type ==1:
#                 self.redirect('http://www.baidu.com')
#             else:
#                 self.redirect('http://www.jd.com')
#         return wrapper
#     return interfacetime
from util.comm import get_ali_object
from util.captcha.captcha import captcha
import requests
import json
class User1Handler(BaseHandler):
    def get(self):
        #获取支付返回的参数
        data = self.request.arguments
        #对参数进行处理
        data = {k:v[0].decode() for k,v in data.items()}
        #从字典中将sign删除
        sign = data.pop("sign")
        #获取支付宝对象
        alipay = get_ali_object()
        #调用验签
        flag = alipay.verify(data,sign)
        print(flag)
        if flag == True:
            #删除队列中的订单
            orderno = data['out_trade_no']
            r.sortedset_delete("cancelorderlist",orderno)
            # #事务处理
            # try:
            #     #更新充值订单状态
            #     sql1= "update"
            #     db.update1(sql1)
            #     #更新用户账号金额
            #     sql2= "update"
            #     db.update1(sql2)
            #     #写入金额记录表
            #     sql3= "insert into"
            #     db.update1(sql3)
            #     db.commit()
            # except:
            #     db.rollback()
      

    #     code = self.get_query_argument("code")
    #     data = {"client_id":'3674019597',"client_secret":"7ae99bc0d54ead29fc8d1b9fabd78587",
    # "grant_type":"authorization_code",
    # 'redirect_uri':'http://127.0.0.1:8000/user/weiboCallback/','code':code}
    #     res1 = requests.post('https://api.weibo.com/oauth2/access_token',data=data)
    #     print(res1.text)
    #     mes = json.loads(res1.text)
    #     #获取在微博平台的用户信息
    #     uid = mes['uid']
    #     token = mes['access_token']
    #     #uid token
    #     #查询此uid是否存在
    #     sql = "select u.id,u.mobile from user as u inner join sf_login as sl on u.id=sl.userid where sl.uid='%s'"%(uid)
    #     user = db.findOne(sql)
    #     #存在
    #     if user:
    #         #生成token,跳转到vue中转页，
    #         pass
    #     else:
    #         self.redirect("http://locallhost:8080/#/bindmobile?uid="+uid+"&token="+token)

    def post(self):
        #获取手机号、uid、token
        mobile= 123
        uid=23
        token=234
        #查询user表中手机号
        sql="select * from user where mobile='%s'"%(mobile)
        res = db.findOne(sql)
        #如果存在，写入三方登录表
        if res:
            s = "insert into sf_login(userid,webfrom,uid,token) values(%d,'wb','%s')"
        #如果不存在，写入user表再写入三方登录表
import os,base64,urllib
def get_file_content_as_base64(path, urlencoded=False):
    """
    获取文件base64编码
    :param path: 文件路径
    :param urlencoded: 是否对结果进行urlencoded 
    :return: base64编码信息
    """
    with open(path, "rb") as f:
        content = base64.b64encode(f.read()).decode("utf8")
        if urlencoded:
            content = urllib.parse.quote_plus(content)
    return content


from util.bdapi import bd
from qiniu import Auth
import uuid
class UserHandler(BaseHandler):
    def get(self):
        access_key = '10XJP3-oMzY2Ghrwsm6nc-fr1OKu_-HcRwweQ1AB'
        secret_key = 'L3yUOFzGq3zJwqy924JPvMg61H88COZZ8feUcAJj'
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'h2203test'
        # 生成上传 Token
        token = q.upload_token(bucket_name)
        return self.finish({"token":token})
        # client_id="3674019597"
        # redirect_uri="http://127.0.0.1:8000/user/weiboCallback/"
        # url="https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code"%(client_id,redirect_uri)
        # self.finish({"code":200,'url':url})
        # clientid="nyyde9oLbRvGmkrpL0Atx66c"
        # secret="neHe5r6wcXfzUWr3qsFpU5rtRicMGnuU"
        # url = "https://aip.baidubce.com/oauth/2.0/token?client_id=%s&client_secret=%s&grant_type=client_credentials"%(clientid,secret)
    
        # payload = ""
        # headers = {
        #     'Content-Type': 'application/json',
        #     'Accept': 'application/json'
        # }
        
        # response = requests.request("POST", url, headers=headers, data=payload)
        # mes =json.loads(response.text)
        # print(response.text)
        # token = mes['access_token']


        # url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=%s"%(token)
    
        # payload='url=http%3A%2F%2Frpuhgscze.hb-bkt.clouddn.com%2F1.jpg'
        # headers = {
        #     'Content-Type': 'application/x-www-form-urlencoded',
        #     'Accept': 'application/json'
        # }
        
        # response = requests.request("POST", url, headers=headers, data=payload)
        
        # print(response.text)

        # uuid = self.get_query_argument("uuid")
        # name, text, img=captcha.generate_captcha()
        # #获取uuid
        # r.set_str(uuid,text)
        # self.set_header("Content-Type","image/jpg")
        # self.write(img)
        
        # self.request.remote_ip
        # name, text, img = captcha.generate_captcha()
        # print(name)
        # print(text)
        # self.set_header('Content-Type', 'image/jpg')
        # self.write(img)
    # @getinterfacetime(2)
    def post(self):
        files = self.request.files.get("file")
        for i in files:
            filename = i['filename']
            #对图片重命名，防止覆盖
            arr = filename.split(".")
            name = uuid.uuid1().hex
            newname = name+"."+arr[1]
            path = os.path.join(self.settings['MEDIA_ROOT'],newname)

            with open(path,'wb') as r:
                r.write(i['body'])
           
            r.list_rpush('baiduapi',path)
            # content = bd.contentmes(path)
            # print(content)
            self.finish({"url":path})
       
        
        self.write("name 23is post:")
import time
def getBaidu():
    while True:
         list = r.list_getall('baiduapi',0,1)
         for i in list:
              content = bd.contentmes(i)
              r.set_str(i,json.dumps(content))
              r.list_lpop("baiduapi")
         time.sleep(1)




#通过角色id获取资源列表的方法
def getMenu(roleid):
    sql="select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resourceid=res.id  inner join resource as pres on res.pid=pres.id where rr.userid=%d and res.type=1"%(int(roleid))
    res = db.findAll(sql)

    reslist=[]
    ids=[]
    pomitionlist=[]
    #遍历查询结果
    for i in res:
        #用户可访问的权限列表
        pomitionlist.append(i['url'])
        #判断父类是否存在，不存在添加
        if i["pid"] not in ids:
            ids.append(i['pid'])
            reslist.append({"id":i["pid"],"name":i['pname'],"son":[{"id":i['id'],"name":i['name'],'url':i['url']}]})
        else:
            #存在，查找父类，遍历父类用子类的pid对比
            for (index,p) in enumerate(reslist):
                if i['pid'] == p['id']:
                    #将子类加到父类下
                    reslist[index]['son'].append({"id":i['id'],"name":i['name'],'url':i['url']})
    return reslist,pomitionlist

def getinterfacelist(roleid):
    sql = "select res.url from role_resource as rr inner join resource as res on rr.resourceid=res.id where rr.userid=%d and res.type=2"%(int(roleid))
    res = db.findAll(sql)
    return res
class LoginHandler(BaseHandler):
    def post(self):
        #获取用户名密码
        data = json.loads(self.request.body)
        name = data['name']
        passwd = data['password']
        # name = self.get_body_argument("name")
        # passwd = self.get_body_argument("password")
        # print(md5(password))
        # return 'ok'
        #判断是否为空，为空返回
        if not all([name,passwd]):
            self.finish({"code":10010,"mes":"必须输入用户名和密码"})
        #去数据库中查询
        sql = "select * from admin_user where username='%s'"%(str(name))
        user = db.findOne(sql)
        if user:
            #密码对比
            newpwd = md5(passwd)
            if newpwd == user['password']:
                #生成token
                data = {"data": {"name": user['username'], "userid": user['id'],"roleid":user['roleid'],"exp":time.time()}}
                token = myjwt.jwt_en(data)
                #获取角色id获取资源列表的方法
                menulist,pomitionlist=getMenu(user['roleid'])
                #通过roleid获取接口权限
                interlist = getinterfacelist(user['roleid'])
                #存在redis
                key = "interlist"+str(user['roleid'])
                r.set_str(key,json.dumps(interlist))
                redata = {"code":200,"token":token,'name':user['name'],"pomitionlist":pomitionlist,'id':user['id'],'mpstatus':user['mpstatus'],'roleid':user['roleid'],'menulist':menulist}
                #返回id,mpstatus(修改密码状态),token,roleid,menulist
                self.finish(redata)
            else:
                self.finish({"code":10012,"mes":"密码不正确"})
        else:
            self.finish({"code":10011,"mes":"用户不存在"})

class LoginOutHandler(BaseHandler):
    def get(self):
        token = self.request.headers['token']
        key = "logoutlist"
        r.sortedset_add(key,token,int(time.time()))
        self.finish({"code":200})